/**
 * Name: Paul Rosa
 *
 * Date: January 12 2012
 */

import java.util.Random;

public class ArrayUtil {

	/**
	 * Precondition: length > 0 Postconditon: Creates an array filled with
	 * 'length' number of random values between 1 and n.
	 * 
	 * @param length:
	 *            the length of the array
	 * @param n:
	 *            the number of possible random values
	 * @return an array filled with 'length' numbers between 0 and n-1
	 */
	public static int[] randomIntArray(int length, int n) {
		int[] temp = new int[length];
		for (int i = 0; i < length; i++) {
			temp[i] = generator.nextInt(n);
		}
		return temp;
	}

	public static String printArray(int[] a, int start, int end) {
		String out = a[start] + "";
		for (int i = start + 1; i <= end; i++)
			out += "," + a[i];
		return out;
	}

	/**
	 * Precondition: 0 <= from < a.length Postcondition: Finds the smallest
	 * element in a tail range of the array.
	 * 
	 * @param from:
	 *            the first position in 'a' to compare
	 * @return the position of the smallest element in the range a[from] . . .
	 *         a[a.length - 1]
	 */
	public static  int minimumPosition(int from, int[] a) {
		int minI = from;
		for (int i = from; i < a.length; i++)
			if (a[minI] >= a[i])
				minI = i;
		return minI;
	}

	/**
	 * Precondition: 0 <= i < a.length, 0 <= j < a.length Postcondition: Swaps
	 * two entries of the array.
	 * 
	 * @param i:
	 *            the first position to swap
	 * @param j:
	 *            the second position to swap
	 */
	public static  void swap(int i, int j, int[] a) {
		int oi = a[i];
		int oj = a[j];
		a[i] = oj;
		a[j] = oi;
	}

	/**
	 * Precondition: 0 <= start <= end < a.length Postcondition: Prints the
	 * values of the array from start to end inclusive.
	 * 
	 * @param start:
	 *            the first position to print
	 * @param end:
	 *            the last position to print.
	 */
	public static String printArray(int start, int end, int[] a) {
		return ArrayUtil.printArray(a, start, end);
	}

	public static  int findIndexToInsert(int insertNum, int[] a) {
		for (int i = 0; i < a.length; i++)
			if (a[i] >= insertNum)
				return i;
		return a.length;
	}

	public static int[] insetSorted(int insertSorted, int[] a) {
		int where = findIndexToInsert(insertSorted,a);
		int[] t = new int[a.length + 1];
		for (int i = 0; i < t.length; i++) {
			if (i == where)
				t[i] = insertSorted;
			else if (i > where)
				t[i] = a[i - 1];
			else
				t[i] = a[i];
		}
		return t;
	}

	private static Random generator = new Random();
}